package translinkApp.DataTypes.Contacts;

import java.util.ArrayList;
import java.util.Collections;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;

public class ContactAddresses {

	public static ArrayList<ContactAddressList> getContactAddresses(final Context context) {
		
		final ArrayList<ContactAddressList> addresses = new ArrayList<ContactAddressList>();

		ContentResolver cr = context.getContentResolver();
		Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
		if (cur.getCount() > 0) {
			while (cur.moveToNext()) {
				String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
				String name = cur.getString(cur
						.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

				ContactAddressList address = getContactAddress(context, cr, id, name);

				address.setContactID(Integer.parseInt(id));

				if (address.size() > 0) {
					addresses.add(address);
				}
			}
		}

		Collections.sort(addresses, new ContactAddressListComparator());

		return addresses;

	}

	private static ContactAddressList getContactAddress(Context context, ContentResolver cr,
			String id, String name) {

		String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
				+ ContactsContract.Data.MIMETYPE + " = ?";
		String[] addrWhereParams = new String[] { id,
				ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };
		Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI, null, addrWhere,
				addrWhereParams, null);

		ContactAddressList addresses = new ContactAddressList();
		addresses.setName(name);
		while (addrCur.moveToNext()) {

			String street = addrCur.getString(addrCur
					.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
			String city = addrCur.getString(addrCur
					.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));

			addresses.add(new ContactAddress(street, city));

		}
		addrCur.close();

		return addresses;

	}

}
